package com.nnxy.controller;
import com.nnxy.pojo.Clazz;
import com.nnxy.pojo.Emp;
import com.nnxy.pojo.PageResult;
import com.nnxy.pojo.Result;
import com.nnxy.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

@RestController
public class ClazzController {
    @Autowired
    private ClazzService clazzService;
    @GetMapping("/clazzs")
    public Result page(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10")  Integer pageSize,
            String name,
            @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
            @DateTimeFormat(pattern = "yyyy-MM-dd")  LocalDate end
    ){
        //1.调用业务层进行分页查询数据返回PageResult
        PageResult<Clazz> pageResult = clazzService.findByPage(page, pageSize, name, begin, end);
        //2.封装Result返回
        return new Result(1,"success",pageResult);
    }

    @GetMapping("/clazzs/list")
    public Result queryAllClazz() {
        Result res;
        try {
            List<Clazz> list = clazzService.queryAllClazz();
            res = new Result(1, "success", list);
        } catch (Exception e) {
            res = new Result(0, "fail", null);
        }
        return  res;
    }


    @PostMapping("/clazzs")
    public Result add(@RequestBody Clazz clazz){
        try {
            clazzService.add(clazz);
            return new Result(1,"success",null);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(0,"添加班级失败.",null);
        }
    }

    @GetMapping("/emps/list")
    public Result list(){
        List<Emp> list=clazzService.list();
        return new Result(1,"success",list);
    }

    @GetMapping("/clazzs/{id}")
    public Result findById(@PathVariable Integer id){
        Clazz clazz = clazzService.findById(id);
        return new Result(1,"success",clazz);
    }

    @PutMapping("/clazzs")
    public Result modify(@RequestBody Clazz clazz) {
        try {
            if (clazz.getName().trim().isEmpty()) {
                throw new IllegalArgumentException("班级名称不能只包含空格");
            }
            if (clazz.getRoom().trim().isEmpty()) {
                throw new IllegalArgumentException("班级教室不能只包含空格");
            }
            clazzService.modify(clazz);
            return new Result(1,"success",null);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(0,"数据插入失败，请联系管理员",null);
        }
    }

    @DeleteMapping("clazzs/{id}")
    public Result delete(@PathVariable Integer id){

        boolean hasEmployees=clazzService.hasEmployees(id);
        if(hasEmployees){
            return new Result(0, "对不起, 该班级下有学生, 不能直接删除", null);
        }
        clazzService.removeById(id);
        return new Result(1, "success", null);
    }
}
